package com.datawin.taotaocheche.ui.actviity;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.jakewharton.rxbinding.widget.RxRadioGroup;
import com.datawin.taotaocheche.R;
import com.datawin.taotaocheche.base.BaseActivity;
import com.datawin.taotaocheche.comm.MyType;
import com.datawin.taotaocheche.comm.RetrofitHelp;
import com.datawin.taotaocheche.event.CloseActEvent;
import com.datawin.taotaocheche.event.NetErrorEvent;
import com.datawin.taotaocheche.ui.fragment.ClueFrag;
import com.datawin.taotaocheche.ui.fragment.CustomClueFrag;
import com.datawin.taotaocheche.ui.fragment.GrabHallFrag;
import com.datawin.taotaocheche.ui.fragment.MineFrag;
import com.datawin.taotaocheche.ui.fragment.OwnerFrag;
import com.datawin.taotaocheche.util.LogUtils;
import com.datawin.taotaocheche.util.SysUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import rx.functions.Action1;

public class MainActivity extends BaseActivity {

    long time;
    @Bind(R.id.main_framelayout)
    FrameLayout content;
    @Bind(R.id.clue)
    RadioButton clue;
    @Bind(R.id.owner)
    RadioButton owner;
    @Bind(R.id.mine)
    RadioButton mine;
    @Bind(R.id.navi)
    RadioGroup navi;


    FragmentManager fm;
    Fragment cf;//记录当前fragment
    String ct;//当前tag

    public final static String CLUE = "线索";
    public final static String OWNER = "我抢的";
    public final static String MINE = "我的";
    private final static String TAG = "current_fragment";

    private Fragment cluefra;
    private Fragment ownerfra;
    private Fragment minefra;

    @Override
    protected void setRoot() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#04C9D7"));
        }
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        fm = getSupportFragmentManager();
        if (savedInstanceState != null) {
            cluefra = fm.findFragmentByTag(CLUE);
            ownerfra = fm.findFragmentByTag(OWNER);
            minefra = fm.findFragmentByTag(MINE);

            for (Fragment fra : fm.getFragments()) {
                if (!fra.isHidden()) {
                    fm.beginTransaction().hide(fra).commit();
                }
                switch ((int) savedInstanceState.getSerializable(TAG)) {
                    case R.id.clue:
                        clue.setChecked(true);
                        break;

                    case R.id.owner:
                        owner.setChecked(true);
                        break;

                    case R.id.mine:
                        mine.setChecked(true);
                        break;

                }
            }
        }
//        setNaviImageSize();
        RxRadioGroup.checkedChanges(navi)
                .compose(this.<Integer>bindToLifecycle())
//                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        switch (integer) {
                            case R.id.clue:
                                if (cluefra == null) {
                                    cluefra = new CustomClueFrag();
                                }
                                changFra(cluefra, CLUE);
                                break;

                            case R.id.owner:
                                if (ownerfra == null) {
                                    ownerfra = new GrabHallFrag();
                                }
                                changFra(ownerfra, OWNER);
                                break;

                            case R.id.mine:
                                if (minefra == null) {
                                    minefra = new MineFrag();
                                }
                                changFra(minefra, MINE);
                                break;

                        }
                    }
                });
        owner.setChecked(true);
    }

    private void setNaviImageSize() {
        for (int i = 0; i < navi.getChildCount(); i++) {
            RadioButton rb = ((RadioButton) navi.getChildAt(i));
            Drawable[] drawables = rb.getCompoundDrawables();
            drawables[1].setBounds(0, 0, SysUtils.dip2px(this, 24), SysUtils.dip2px(this, 24));
            rb.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
        }
    }

    private void changFra(Fragment fra, String tag) {
        ct = tag;
        if (fm.findFragmentByTag(tag) == null) {
            if (cf != null) {
                fm.beginTransaction().hide(cf).add(R.id.main_framelayout, fra, tag).commit();
            } else {
                fm.beginTransaction().add(R.id.main_framelayout, fra, tag).commit();
            }
            cf = fra;
            return;
        }
        if (fra.isHidden()) {
            if (cf != null) {
                fm.beginTransaction().hide(cf).show(fra).commit();
            } else {
                fm.beginTransaction().show(fra).commit();
            }
            cf = fra;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseActEvent(CloseActEvent event) {
        if (event.getType() == MyType.Logout) {
            finishAct();
        }
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(TAG, navi.getCheckedRadioButtonId());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - time <= 2000L) {
                LogUtils.d("我退出APP啦");
                RetrofitHelp.logout();
                finishAct();
                System.exit(0);
            } else {
                showMsg("再按一次退出程序");
                time = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
